/*
 * @Descripttion: 业务数据缓存
 * @version: 1.0
 * @LastEditors: lzt
 * @LastEditTime: 2023-11-25
 */

import tool from '@/utils/tool';
import api from "@/api";
import http from "@/utils/request";
import {h} from "vue";
import {ElButton, ElTag} from "element-plus";
import store from "@/store";
import constant from "@/constant";
import db from "@/utils/db";
import ExLabel from "@/components/exLabel/index.vue";

const cache = {}


function lockKey(dataKey) {
	return "LOCK_" + dataKey;
}

function urlKey(dataKey) {
	return "URL_" + dataKey;
}

function storeKey(key, params) {
	//获取请求参数的MD5值作为缓存key的后缀
	let paramArray = [];
	for (let param in params) {
		paramArray.push(param);
	}
	if (paramArray.length > 0) {
		paramArray = paramArray.sort();
		let tempStr = "";
		paramArray.forEach(item => {
			tempStr = tempStr + item + params[item];
		})
		let cryptoKey = tool.crypto.MD5(tempStr);
		return key + "_" + cryptoKey;
	}
	return key;
}

function urlData(name, url, params) {
	return {name: name, url: url, params: params};
}

async function cacheTreeData(cacheKey, data, expired) {
	tool.data.remove(cacheKey);
	let dbName = "masterDB";
	let tableName = "TREE_TABLE";
	let storeData = {cacheKey: cacheKey, content: tool.toJsonString(data)}
	let treeDatabase = await db.open(dbName);
	await treeDatabase.delete(tableName, cacheKey);
	try {
		await treeDatabase.add(tableName, storeData);
	}catch (e){
		await treeDatabase.put(tableName, storeData);
	}
	treeDatabase.close();
	tool.data.set(cacheKey, true, expired);
}

async function getTreeData(cacheKey) {
	let dbName = "masterDB";
	let tableName = "TREE_TABLE";
	let treeDatabase = await db.open(dbName);
	let data = await treeDatabase.get(tableName, cacheKey);
	treeDatabase.close();
	if (data) {
		return tool.toObj(data.content);
	}
	return null;
}

async function clearTreeData(cacheKey) {
	let dbName = "masterDB";
	let tableName = "TREE_TABLE";
	let treeDatabase = await db.open(dbName);
	await treeDatabase.delete(tableName, cacheKey);
	treeDatabase.close();
	tool.data.remove(cacheKey);
}


async function cacheDictData(cacheKey, data, expired) {
	tool.data.remove(cacheKey);
	let dbName = "masterDB";
	let tableName = "DICT_TABLE";
	let storeData = {cacheKey: cacheKey, content: tool.toJsonString(data)}
	let treeDatabase = await db.open(dbName);
	await treeDatabase.delete(tableName, cacheKey);
	try {
		await treeDatabase.add(tableName, storeData);
	}catch (e){
		await treeDatabase.put(tableName, storeData);
	}
	treeDatabase.close();
	tool.data.set(cacheKey, true, expired);
}

async function getDictData(cacheKey) {
	let dbName = "masterDB";
	let tableName = "DICT_TABLE";
	let treeDatabase = await db.open(dbName);
	let data = await treeDatabase.get(tableName, cacheKey);
	treeDatabase.close();
	if (data) {
		return tool.toObj(data.content);
	}
	return null;
}

async function clearDictData(cacheKey) {
	let dbName = "masterDB";
	let tableName = "DICT_TABLE";
	let treeDatabase = await db.open(dbName);
	await treeDatabase.delete(tableName, cacheKey);
	treeDatabase.close();
	tool.data.remove(cacheKey);
}

cache.timer = {
	//开启缓存数据过期检测处理,10秒执行一次
	start: function () {
		setInterval(() => {
			cache.dic.expiredProcess();
			cache.tree.expiredProcess();
		}, 10 * 1000);
	},
	//清除所有定时任务
	stop: function () {
		let timerId = setInterval(() => {
		}, 10000);
		for (let i = 1; i <= timerId; i++) {
			clearInterval(i);
		}
	}
}

cache.websocket = {
	//缓存key的前缀
	PREFIX: "WEB_SOCKET_",
	//清空websocket缓存
	clear: function () {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				tool.data.remove(cacheKey);
			}
		}
	},
}

cache.dic = {
	//字典存储key的前缀
	PREFIX: "DICT_",
	//缓存过期时间，单位秒，0代表不过期
	expired: 0,
	//发送请求
	sendRequest: function (req, params) {
		req.post(params).then(async (rsp) => {
			await this.storeData(rsp, req.url, params);
		});
	},
	//存储数据
	storeData: async function (rsp, url, params) {
		if (rsp.success && rsp.data) {
			let dataObject = {};
			rsp.data.forEach(item => {
				//缓存key
				let key = this.PREFIX + item.dictionaryCode;
				let data = dataObject[key];
				if (!data) {
					data = [];
					dataObject[key] = data;
					//把该数据的请求地址和参数放入缓存，供后续自动更新缓存使用
					params.dictionaryCode = item.dictionaryCode
					tool.data.set(urlKey(key), urlData(item.dictionaryCode, url, params));
				}
				//添加新成员重新放入缓存
				let tempItem = {};
				tempItem.k = item.dictionaryValue;
				tempItem.v = item.dictionaryCodeValue;
				tempItem.l = item.dictionaryRelValue;
				tempItem.n = item.dictionaryFullLabel||item.dictionaryLabel;
				tempItem.e = item.isEnabled;
				if (item.loginName) {//此为操作员
					tempItem.t = true;
				}
				if (item.color) {
					tempItem.c = item.color;
				}
				data.push(tempItem);
			});

			for (let key in dataObject) {
				await cacheDictData(key, dataObject[key], this.expired);
			}
		}
	},
	//重新加载单类数据字典
	reload: async function (dictionaryCode) {
		let key = this.PREFIX + dictionaryCode;
		let urlData = tool.data.get(urlKey(key));
		//存在请求地址，则进行刷新操作
		if (urlData) {
			//检查此操作是否加锁，加锁直接返回
			let lock = tool.data.get(lockKey(key));
			//存在锁时，直接返回
			if (lock) {
				return null;
			}
			//加锁进行数据刷新处理，10秒未处理完，自动解锁
			tool.data.set(lockKey(key), true, 10);
			let params = {dictionaryCode: dictionaryCode};
			let rsp = await http.post(urlData.url, urlData.params);
			await this.storeData(rsp, urlData.url, urlData.params);
			//数据处理完成，释放锁
			tool.data.remove(lockKey(key));
			//重新请求之后再从缓存获取一次（因为请求为异步处理，暂时无效）
			// return tool.data.get(key);
			return await getDictData(key);
		}
		return null;
	},
	//key过期处理
	expiredProcess: function () {
		for (let key in localStorage) {
			if (key.startsWith(this.PREFIX)) {
				let data = tool.data.get(key);
				if (!data) {
					let urlData = tool.data.get(urlKey(key));
					if (urlData) {
						this.reload(urlData.params.dictionaryCode);
					}
				}
			}
		}
	},
	options: async function (dictionaryCode, isPriKey) {
		let key = this.PREFIX + dictionaryCode;
		// let data = tool.data.get(key);
		let data = await getDictData(key);
		//没获取到数据，重新请求加载数据
		if (!data || !Array.isArray(data)) {
			data = await this.reload(dictionaryCode);
		}
		if (data && Array.isArray(data)) {
			let ops = [];
			data.forEach(item => {
				if (item.e === '1' && item.v) {
					let option = {};
					option.label = item.n;
					if (isPriKey) {
						option.value = item.k;
					} else {
						option.value = item.v;
					}
					if (item.t) {
						option.t = item.t;
					}
					ops.push(option);
				}
			});
			return ops;
		} else {
			return [];
		}
	},
	flows: async function (dictionaryCode, flowGroupId) {
		let key = this.PREFIX + dictionaryCode;
		// let data = tool.data.get(key);
		let data = await getDictData(key);
		//没获取到数据，重新请求加载数据
		if (!data || !Array.isArray(data)) {
			data = await this.reload(dictionaryCode);
		}
		if (data && Array.isArray(data)) {
			let ops = [];
			data.forEach(item => {
				if (item.e === '1' && item.v === flowGroupId) {
					let option = {};
					option.label = item.n;
					option.value = item.k;
					ops.push(option);
				}
			});
			return ops;
		} else {
			return [];
		}
	},
	toOptions: function (data, isPriKey) {
		if (data && Array.isArray(data)) {
			let ops = [];
			data.forEach(item => {
				if (item.isEnabled === '1' && item.dictionaryCodeValue) {
					let option = {};
					option.label = item.dictionaryFullLabel||item.dictionaryLabel;
					if (isPriKey) {
						option.value = item.dictionaryValue;
					} else {
						option.value = item.dictionaryCodeValue;
					}
					ops.push(option);
				}
			});
			return ops;
		} else {
			return [];
		}
	},
	/**
	 *
	 * @param dictionaryCode
	 * @param value
	 * @param type id | code | name | levelCode
	 * @returns {Promise<*|string>}
	 */
	convert: async function (dictionaryCode, value, type) {
		if (value === '0000000') {
			return '顶级';
		}
		if (value === '00000000-0000-0000-0000-000000000000') {
			return '未知';
		}
		if (dictionaryCode && value) {
			let key = this.PREFIX + dictionaryCode;
			// let data = tool.data.get(key);
			let data = await getDictData(key);
			//没获取到数据，重新请求加载数据
			if (!data || !Array.isArray(data)) {
				data = this.reload(dictionaryCode);
			}
			if (data && Array.isArray(data)) {
				for (let item of data) {
					//item.v code ,item.k 主健id,item.n 名称 ,item.l 层级代码
					if (item.v === value || item.k === value || item.n === value || item.l === value) {
						if(type==='id'){
							value = item.k;
						}else if(type==='code') {
							value = item.v;
						}else if(type==='levelCode') {
							value = item.l;
						}else{
							value = item.n;
						}
						break;
					}
				}
			}
		}
		return value;
	},
	exLabel: function (dictionaryCode, value, bool) {
		if (value === '0000000') {
			return '顶级';
		}
		if (value === '00000000-0000-0000-0000-000000000000') {
			return '未知';
		}
		return h(ExLabel, {key: dictionaryCode + value, code: dictionaryCode, value: value, bool: bool});
		// return h(ExLabel, {key:tool.uuid('elk'),code: dictionaryCode,value:value,bool:bool});
	},
	label: async function (dictionaryCode, value, bool,removeCode) {
		if (value === '0000000') {
			return '顶级';
		}
		if (value === '00000000-0000-0000-0000-000000000000') {
			return '未知';
		}
		if (dictionaryCode && value) {
			let key = this.PREFIX + dictionaryCode;
			// let data = tool.data.get(key);
			let data = await getDictData(key);
			//没获取到数据，重新请求加载数据
			if (!data || !Array.isArray(data)) {
				data = this.reload(dictionaryCode);
			}
			if (data && Array.isArray(data)) {
				for (let item of data) {
					if (item.k === value || item.v === value || item.l === value) {
						value = item.n;
						if(dictionaryCode==="SysUser"&&removeCode!==true){
							if(item.n!=='Iforo'){
								value = item.n+item.v;
							}
						}
						if (bool===true && item.c) {
							let label = value;
							// if (dictionaryCode === "DOCUMENT_STATUS") {
							// 	value = h(ElTag, {
							// 		size: 'small',
							// 		style: "color:#fff;margin-left: 10px;background-color: " + item.c + ";border-color: " + item.c
							// 	}, () => label);
							// } else {
								value = h(ElTag, {
									size: 'small',
									style: "color:#fff;background-color: " + item.c + "9D;border:1;border-color: " + item.c+"F2;"
								}, () => label);
							// }
						}
						break;
					}
				}
			}
		}
		return value;
	},
	userlabels: async function (dictionaryCode, values, bool) {
		let allvalues="";

		if (dictionaryCode) {
			let key = this.PREFIX + dictionaryCode;
			// let data = tool.data.get(key);
			let data = await getDictData(key);
			//没获取到数据，重新请求加载数据
			if (!data || !Array.isArray(data)) {
				data = this.reload(dictionaryCode);
			}
			if (data && Array.isArray(data)) {

				let num=0;
				for (let value of values) {
					for (let item of data) {
						if (item.k === value || item.v === value || item.l === value) {
							if(num==0){
								allvalues = item.n;
							}else{
								allvalues =allvalues+","+ item.n;
							}

							break;
							}


					}
					num=num+1;
				}
			}
		}
		return allvalues;
	},
	value: async function (dictionaryCode, label, isPriKey) {
		if (dictionaryCode && label) {
			let key = this.PREFIX + dictionaryCode;
			// let data = tool.data.get(key);
			let data = await getDictData(key);
			//没获取到数据，重新请求加载数据
			if (!data || !Array.isArray(data)) {
				data = this.reload(dictionaryCode);
			}
			if (data && Array.isArray(data)) {
				for (let item of data) {
					if (item.n === label) {
						if (isPriKey) {
							label = item.k;
						} else {
							label = item.v;
						}
						break;
					}
				}
			}
		}
		return label;
	},
	//初始化数据字典
	init: function () {
		this.initEntityGroup();
		this.autoInit();
	},
	//初始大数据
	initBigData: async function () {
		let cacheKey = "DICT_SysUser"
		let data = await getDictData(cacheKey);
		if (data == null) {
			this.sendRequest(api.system.operator.dataDictionaries, {});
		}
	},
	initEntityGroup() {
		let dictionaryCode = "ENTITY_DICT";
		let key = this.PREFIX + dictionaryCode;
		let data = [];
		for (let item in constant.entity) {
			let dict = {};
			dict.k = constant.entity[item].name;
			dict.v = constant.entity[item].name;
			dict.n = constant.entity[item].label;
			dict.d = dictionaryCode;
			dict.e = "1";
			data.push(dict);
		}
		// tool.data.set(key, data);
		cacheDictData(key, data);
	},
	autoInit() {
		for (let module in api) {
			if ((api[module] instanceof Object) && !Array.isArray(api[module])) {
				for (let entity in api[module]) {
					if ((api[module][entity] instanceof Object) && !Array.isArray(api[module][entity])) {
						if (api[module][entity]['dataDictionaries']) {
							this.sendRequest(api[module][entity]['dataDictionaries'], {});
						}
						if (api[module][entity]['treeData'] && api[module][entity]['treeData'].storeName) {
							tool.data.set(api[module][entity]['treeData'].storeName + "_TREE_API_URL", api[module][entity]['treeData'].url);
						}
						if (api[module][entity]['findById'] && api[module][entity]['findById'].storeName) {
							tool.data.set(api[module][entity]['findById'].storeName + "_ID_API_URL", api[module][entity]['findById'].url);
						}
					}
				}
			}
		}
	},
}

cache.tree = {
	//缓存key的前缀
	PREFIX: "TREE_",
	//缓存过期时间，单位秒，0代表不过期
	expired: 0,
	//发送请求
	sendRequest: async function (name, url, params) {
		if (url && params) {
			let rsp = await http.post(url, params);
			await this.storeData(rsp, name, url, params);
			return rsp.data;
		}
		return null;
	},
	//存储数据
	storeData: async function (rsp, name, url, params) {
		if (rsp.success && rsp.data) {
			let key = this.PREFIX + name;
			let cacheKey = storeKey(key, params)
			//不管之前有没有数据，请清空此key的缓存数据
			// tool.data.remove(cacheKey);
			//放入最新请求的数据
			// tool.data.set(cacheKey, rsp.data, this.expired);
			await cacheTreeData(cacheKey, rsp.data, this.expired);
			//把该数据的请求地址和参数放入缓存，供后续自动更新缓存使用
			tool.data.set(urlKey(cacheKey), urlData(name, url, params));
		}
	},
	//重新加载单类数据字典
	reload: async function (name, params) {
		//缓存名称为空，直接返回
		if (!name) {
			return null;
		}
		let url = tool.data.get(name + "_TREE_API_URL");
		if (!url) {
			return null;
		}

		let key = this.PREFIX + name;
		//如果参数为空，则从缓存中获取url和参数的信息，重新加载
		if (!params) {
			for (let cacheKey in localStorage) {
				if (cacheKey.startsWith(key)) {
					let urlData = tool.data.get(urlKey(cacheKey));
					if (urlData) {
						urlData.params.toServer = true;
						this.reload(name, urlData.params);
					}
				}
			}
			return null;
		}
		//判断是否需要从服务器加载数据
		let needClearData = false;
		if (params.toServer) {
			needClearData = true;
			delete params.toServer;
		}

		//获取请求参数的MD5值作为缓存key的后缀
		let cacheKey = storeKey(key, params);
		//如果需要从服务器加载数据，则先删除缓存数据
		if (needClearData) {
			tool.data.remove(cacheKey);
		}

		//先从缓存获取数据
		let data = tool.data.get(cacheKey);
		//获取到数据直接返回
		if (data) {
			return await getTreeData(cacheKey);
		}

		//缓存无数据，向服务器发起请求
		//检查此操作是否加锁，加锁直接返回
		let lock = tool.data.get(lockKey(cacheKey));
		//存在锁时，直接返回
		if (lock) {
			//暂时不返回空
			// return null;
		}
		//加锁进行数据刷新处理，10秒未处理完，自动解锁
		tool.data.set(lockKey(cacheKey), true, 10);
		let result = await this.sendRequest(name, url, params);
		tool.data.remove(lockKey(cacheKey));
		return result;
	},
	options: async function (name, params) {
		let data = await this.reload(name, params);
		if (data) {
			this.addDisabled(data);
		}
		return data;
	},
	addDisabled(data) {
		if (Array.isArray(data)) {
			data.forEach(item => {
				item.disabled = item.isEnabled !== '1';
				if (item.children) {
					this.addDisabled(item.children);
				}
			});
		}
	},
	clear: function (name) {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX) && cacheKey.includes(name)) {
				console.log("cache.tree.clear", cacheKey);
				tool.data.remove(cacheKey);
				// clearTreeData(cacheKey);
			}
		}
	},
	clearAll: function () {
		console.log("cache.tree.clear", "all");
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				tool.data.remove(cacheKey);
			}
		}
	},
	autoInit() {
		for (let module in api) {
			if ((api[module] instanceof Object) && !Array.isArray(api[module])) {
				for (let entity in api[module]) {
					if ((api[module][entity] instanceof Object) && !Array.isArray(api[module][entity])) {
						if (api[module][entity]['treeData'] && api[module][entity]['treeData'].storeName) {
							let storeName = api[module][entity]['treeData'].storeName
							tool.data.set(storeName + "_TREE_API_URL", api[module][entity]['treeData'].url);
							if (storeName === 'FamsAssetCategory' || storeName === 'SysOrganization')
								this.reload(storeName, {parentLevelCode: '0000000'});
						}
					}
				}
			}
		}
	},
	//key过期处理
	expiredProcess: function () {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				let data = tool.data.get(cacheKey);
				if (!data) {
					let urlData = tool.data.get(urlKey(cacheKey));
					if (urlData) {
						this.reload(urlData.name);
					}
				}
			}
		}
	},
}

cache.data = {
	//缓存key的前缀
	PREFIX: "CACHE_DATA_",
	//缓存过期时间，单位秒，0代表不过期
	expired: 0,
	//发送请求
	sendRequest: async function (name, url, params) {
		if (url && params) {
			let rsp = await http.post(url, params);
			this.storeData(rsp, name, url, params);
			return rsp.data;
		}
		return null;
	},
	//存储数据
	storeData: function (rsp, name, url, params) {
		if (rsp.success && rsp.data) {
			let key = this.PREFIX + name;
			let cacheKey = storeKey(key, params)
			//不管之前有没有数据，请清空此key的缓存数据
			tool.data.remove(cacheKey);
			//放入最新请求的数据
			tool.data.set(cacheKey, rsp.data, this.expired);
			//把该数据的请求地址和参数放入缓存，供后续自动更新缓存使用
			tool.data.set(urlKey(cacheKey), urlData(name, url, params));
		}
	},
	//重新加载单类数据字典
	reload: async function (name, url, params) {
		//缓存名称为空，直接返回
		if (!name) {
			return null;
		}

		let key = this.PREFIX + name;
		//如果url或参数为空，则从缓存中获取url和参数的信息，重新加载
		if (!url || !params) {
			for (let cacheKey in localStorage) {
				if (cacheKey.startsWith(key)) {
					let urlData = tool.data.get(urlKey(cacheKey));
					if (urlData) {
						urlData.params.toServer = true;
						this.reload(name, urlData.url, urlData.params);
					}
				}
			}
			return null;
		}
		//判断是否需要从服务器加载数据
		let needClearData = false;
		if (params.toServer) {
			needClearData = true;
			delete params.toServer;
		}

		//获取请求参数的MD5值作为缓存key的后缀
		let cacheKey = storeKey(key, params);
		//如果需要从服务器加载数据，则先删除缓存数据
		if (needClearData) {
			tool.data.remove(cacheKey);
		}

		//先从缓存获取数据
		let data = tool.data.get(cacheKey);
		//获取到数据直接返回
		if (data) {
			return data;
		}

		//缓存无数据，向服务器发起请求
		//检查此操作是否加锁，加锁直接返回
		let lock = tool.data.get(lockKey(cacheKey));
		//存在锁时，直接返回
		if (lock) {
			return null;
		}
		//加锁进行数据刷新处理，10秒未处理完，自动解锁
		tool.data.set(lockKey(cacheKey), true, 10);
		let result = await this.sendRequest(name, url, params);
		tool.data.remove(lockKey(cacheKey));
		return result;
	},
	//key过期处理
	expiredProcess: function () {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				let data = tool.data.get(cacheKey);
				if (!data) {
					let urlData = tool.data.get(urlKey(cacheKey));
					if (urlData) {
						this.reload(urlData.name);
					}
				}
			}
		}
	},

	loadColumnGroups: async function () {
		//查询所有字段信息
		let columns = await this.reload("FamsColumns", api.asset.column.all.url, {isGroup: '0'});
		let columnGroups = [];
		if (columns) {
			columns.forEach((column, position) => {
				//字段样式的默认属性
				let columnStyle = {
					columnId: column.id,
					isReadonly: '0',
					isRequired: '0',
					colSpan: 0,
					minValue: 0,
					minLength: 0,
					groupPosition: position,
					defaultValue: null,
					visible: true,
				};
				Object.assign(column, columnStyle);

				let columnGroup = columnGroups.filter(group => group.levelCode === column.parentLevelCode)[0];
				if (columnGroup) {
					columnGroup.items.push(column)
				} else {
					columnGroup = {levelCode: column.parentLevelCode, items: []};
					columnGroup.items.push(column)
					columnGroups.push(columnGroup);
				}
			});
		}
		return columnGroups;
	},
	loadColumn: async function (columnId) {
		//查询所有字段信息
		let columns = await this.reload("FamsColumns", api.asset.column.all.url, {isGroup: '0'});
		if (columns && Array.isArray(columns)) {
			for (let column of columns) {
				if (columnId === column.id) {
					return column;
				}
			}
		}
		return {};
	},
	loadGlobalParam: async function (paramCode) {
		let key = this.PREFIX + "SysGlobalParam" + paramCode;
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (data) {
			return data;
		}
		let res = await api.system.globalParam.load.post({});
		if (res.code === 2000) {
			let params = res.data;
			if (Array.isArray(params)) {
				params.forEach(item => {
					item.paramValue = tool.toObj(item.paramValue);
					tool.data.set(this.PREFIX + "SysGlobalParam" + item.paramCode, item.paramValue);
				});
				return tool.data.get(key);
			}
		}
		return null;
	},
	loadDataCard: async function (cardId) {
		let key = this.PREFIX + "FamsAssetCard" + cardId;
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (data) {
			return data;
		}
		let rsp = await api.asset.card.findById.post({id: cardId});
		if (rsp.code === 2000) {
			tool.data.set(key, rsp.data);
			return rsp.data;
		}
		return null;
	},
	loadAssetCategory: async function (assetCategoryId) {
		let key = this.PREFIX + "FamsAssetCategory" + assetCategoryId;
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (data) {
			return data;
		}
		let rsp = await api.asset.assetcategory.findById.post({id: assetCategoryId});
		if (rsp.code === 2000) {
			tool.data.set(key, rsp.data);
			return rsp.data;
		}
		return null;
	},
	loadColumns: async function (assetCategoryId) {
		let key = this.PREFIX + "FamsColumn" + assetCategoryId;
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (data) {
			return data;
		}
		let rsp = await api.asset.assetcategory.loadColumns.post({id: assetCategoryId});
		if (rsp.code === 2000) {
			tool.data.set(key, rsp.data);
			return rsp.data;
		}
		return null;
	},
	loadDocumentConfig: async function (configId) {
		let key = this.PREFIX + "FamsDocumentConfig" + configId;
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (data) {
			return data;
		}
		let rsp = await api.asset.documentConfig.findById.post({id: configId});
		if (rsp.code === 2000) {
			tool.data.set(key, rsp.data);
			return rsp.data;
		}
		return null;
	},
	loadDocumentProcessType: async function (configId) {
		let key = this.PREFIX + "FamsDocumentProcessType";
		//先从缓存获取数据
		let data = tool.data.get(key);
		//获取到数据直接返回
		if (!data) {
			let rsp = await api.asset.processType.data.post({});
			if (rsp.code === 2000) {
				tool.data.set(key, rsp.data);
				data = rsp.data;
			}
		}
		if (data && Array.isArray(data)) {
			let ops = [];
			data.forEach(item => {
				if (item.isEnabled === '1'&&item.configId===configId) {
					let option = {};
					option.label = item.name;
					option.value = item.id;
					ops.push(option);
				}
			});
			return ops;
		} else {
			return [];
		}
	},
	clear: function (name) {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX) && cacheKey.includes(name)) {
				console.log("cache.data.clear", name);
				tool.data.remove(cacheKey);
			}
		}
		if ("SysGlobalParam" === name) {
			this.loadGlobalParam("_ALL");
		}
	},
	clearAll: function () {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				tool.data.remove(cacheKey);
			}
		}
		this.loadGlobalParam("_ALL");
		console.log("cache.data.clear", "clearAll");
	},
}

cache.login = {
	assemble: async function (loginResult, isProxyLogin,_this) {
		let dataInitFinish = false;
		while (!dataInitFinish) {//检查初始化数据是否已经准备就绪
			let cacheKey = "DICT_SysUser"
			let data = await getDictData(cacheKey);
			if (data != null) {
				dataInitFinish = true;
				console.log("初始化完成", dataInitFinish);
			}
		}
		//读取角色和角色对应的资源信息，组装成前端数据格式
		let roles = loginResult.map.userRoles;
		let roleResources = loginResult.map.roleResources;
		if (!roles[0] || roleResources[roles[0].id].length === 0) {
			_this.$message.warning({message: this.$t('login.NO_AUTH')});
			return false;
		}

		let authMap = {};
		if (roles) {
			roles.forEach(role => {
				let data = {role: role};
				if (roleResources) {
					let resources = roleResources[role.id];
					if (resources) {
						//分离菜单和按钮
						let buttons = [];
						let menus = [];
						resources.forEach(item => {
							if (item.isEnabled === '1') {
								if (item.resourceType === '0') {
									menus.push(item);
								} else {
									buttons.push(item.parentLevelCode + item.menuAddress);
								}
							}
						});
						let menuTree = this.menuTree(menus, '0000000');
						data.buttons = buttons;
						data.menuTree = menuTree;
					}
				}
				authMap[role.id] = data;
			});
		}

		tool.data.set("USER_INFO", loginResult.map.userInfo);
		tool.data.set("USER_DEPT", loginResult.map.userDept);
		tool.data.set("USER_TOKEN", loginResult.map.userToken);
		tool.data.set("USER_ROLES", loginResult.map.userRoles);
		tool.data.set("USER_MANAGE_DEPT_IDS", loginResult.map.userManageDeptIds);
		tool.data.set("USER_READ_DEPT_IDS", loginResult.map.userReadDeptIds);
		tool.data.set("USER_INNER_RANGE_DEPT_IDS", loginResult.map.innerRangeDeptIds);
		tool.data.set("USER_POSITIONS", loginResult.map.managePositionIds);
		tool.data.set("AUTH_MAP", authMap);

		let currentRole = tool.data.get("CURRENT_ROLE");
		let auth = null;
		if (currentRole) {//更新为最新角色数据
			auth = authMap[currentRole.id];
		}
		if (!auth) {//默认取第一个角色的数据
			auth = authMap[roles[0].id];
		}
		if (auth) {
			//将按钮放入缓存
			tool.data.set("PERMISSIONS", auth.buttons);
			tool.data.set("MENU", auth.menuTree);
			tool.data.set("CURRENT_ROLE", auth.role);
		}

		if (isProxyLogin) {
			//添加代理登录标识
			tool.data.set("IS_PROXY_LOGIN", true);
			tool.data.remove("REPLACE_JOBS");
		} else {
			//删除代理登录标识
			tool.data.remove("IS_PROXY_LOGIN");
			tool.data.set("REPLACE_JOBS", loginResult.map.replaceJobs);
			tool.data.set("MAIN_LOGIN_USER", loginResult);
		}

		//设置登录的token
		tool.cookie.set("TOKEN", loginResult.data, {
			expires: 24 * 60 * 60
		})

		return true;
	},
	menuTree(menus, parentLevelCode) {
		let menuTree = [];
		//组装菜单
		menus.forEach(item => {
			let menu = {};
			menu.orderWeight = item.orderWeight;
			menu.code = item.levelCode;
			menu.path = item.menuAddress;
			if (!item.menuAddress) {
				menu.path = '/' + item.levelCode;
			} else {
				menu.path = item.menuAddress;
				if (item.menuMode === 'standard' || item.menuMode === 'template') {
					if (item.menuAddress !== '/' && item.menuAddress !== '/index') {
						menu.path = item.menuAddress + '/' + item.levelCode;
					}
				}
			}
			menu.name = item.resourceName;
			menu.component = item.menuPath;
			menu.levelCode = item.levelCode;
			menu.meta = {};
			menu.meta.title = item.resourceName;
			menu.meta.icon = item.menuIcon;
			menu.meta.type = item.menuMode;
			menu.meta.attachParams = item.attachParams;
			menu.meta.relTemplateId = item.relTemplateId;
			menu.meta.isQuickCenter = item.isQuickCenter;
			menu.meta.quickCenterIcon = item.quickCenterIcon;
			menu.meta.levelCode = item.levelCode;
			menu.meta.affix = menu.path === '/' || menu.path === '/index';
			menu.children = [];
			if (item.parentLevelCode === parentLevelCode) {
				menuTree.push(menu);
			}
		});
		menuTree.forEach(item => {
			item.children = this.menuTree(menus, item.levelCode);
		});
		menuTree.sort((a, b) => a.orderWeight - b.orderWeight);
		return menuTree;
	},
}
/*
cache.homemenu = {
	//缓存key的前缀
	PREFIX: "HOMEMENU_",
	//缓存过期时间，单位秒，0代表不过期
	expired: 0,
	//存储数据
	storeData: async function (data, name) {
		if (data) {
			let key = this.PREFIX + name;
			await cacheDictData(key, data, this.expired);
		}
	},
	//取数据
	getStoreData: async function (name) {
		let key = this.PREFIX + name;
		return await getDictData(key);
	},
	addhome(name) {
		var savemenu={
			fullPath:"/index",
			href:"#/index",
			path:"/index",
			name:"首页",
		};
		this.addmenu(savemenu,name);
	},
	//新增数据
	addmenu(currmenu,name) {
		var savemenu={
			fullPath:currmenu.fullPath,
			href:currmenu.href,
			path:currmenu.path,
			name:currmenu.name,
		};

		//console.log(savemenu);
		let data= this.getStoreData(name);
		if (Array.isArray(data)) {
			if(data.findIndex(item=>item.href==savemenu.href)===-1){
				data.push(savemenu);
			}
			this.storeData(savemenu.href,"currmenu")
		}else{
			data=new Array();
			data.push(savemenu);
		}
		this.storeData(data,name);
	},
	//删除数据
	deletemenu(deletemenu,name) {
		var savemenu={
			fullPath:deletemenu.fullPath,
			href:deletemenu.href,
			path:deletemenu.path,
			name:deletemenu.name,
		};
		let data= this.getStoreData(name);
		if (Array.isArray(data)) {
			let NewData=new Array();
			let delflag=false;
			for (let menu in data) {
				if (menu.href==savemenu.href) {
					delflag=true;
				}else{
					if(delflag==true){
						this.storeData(menu.href,"currmenu")
					}
					NewData.push(menu);
				}
			}
			if(delflag==false && data.length>0){
				this.storeData(data[data.length-1].href,"currmenu")
			}
			if(data.length==0){
				this.addhome(name);
			}
			this.storeData(data,name);
		}
	},
	clear: function (name) {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX) && cacheKey.includes(name)) {
				console.log("cache.menu.clear", cacheKey);
				tool.data.remove(cacheKey);
				// clearTreeData(cacheKey);
			}
		}
	},
	clearAll: function () {
		console.log("cache.menu.clear", "all");
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				tool.data.remove(cacheKey);
			}
		}
	},
	//key过期处理
	expiredProcess: function () {
		for (let cacheKey in localStorage) {
			if (cacheKey.startsWith(this.PREFIX)) {
				let data = tool.data.get(cacheKey);
				if (!data) {
					let urlData = tool.data.get(urlKey(cacheKey));
					if (urlData) {
						this.reload(urlData.name);
					}
				}
			}
		}
	},
}
*/
export default cache
